// profile.js
const http = require('../../utils/http.js');

Page({
  data: {
    baseCandidateInfo: {
      id: '',
      id_number: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      political_status_id: '',
      foreign_language_id: '',
      phone: '',
      password: ''
    },
    baomingCandidateInfo: {
      id_number: '',
      vocational_college_id: '',
      vocational_major_id: '',
      candidate_type_id: '',
      exam_center_city_id: '',
      exam_major_id: '',
      volunteer_college_id: '',
      volunteer_major_id: '',
      is_certificate_issued: ''
    },
    postCandidateInfo: {
      id_number: '',
      address: '',
      postal_code: '',
      recipient_name: ''
    },
    expanded: {
      base: false,
      baoming: false,
      post: false
    },
    idToNameMappings: {
      ethnicity: {},
      politicalstatus: {},
      foreignlanguage: {},
      vocationalcollege: {},
      vocationalmajor: {},
      candidateType: {},
      city: {},
      major: {},
      volunteercollege: {},
      volunteermajor: {}
    }
  },
  // 日期格式化函数
  formatDate(dateString) {
    if (!dateString) return '';

    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数
    const day = String(date.getDate()).padStart(2, '0');

    return `${year}-${month}-${day}`;
  },
  onLoad() {
    try {
        const baseInfo = wx.getStorageSync('base_candidate_info');
        const baomingInfo = wx.getStorageSync('baoming_candidate_info');
        const postInfo = wx.getStorageSync('post_candidate_info');

        if (baseInfo) {
            baseInfo.birth_date = this.formatDate(baseInfo.birth_date)
            this.setData({ baseCandidateInfo: baseInfo });
        }

        if (baomingInfo) {
            this.setData({ baomingCandidateInfo: baomingInfo });
        }

        if (postInfo) {
            this.setData({ postCandidateInfo: postInfo });
        }

        // 初始化映射加载状态
        this.setData({ mappingsLoaded: false });

        // 根据 ID 获取对应名称并更新数据
        this.fetchNameMappings();
    } catch (error) {
        console.error('Error loading candidate info from storage:', error);
    }
},


  fetchNameMappings() {
    const mappingFields = {
        ethnicity: 'ethnicity_id',
        politicalstatus: 'political_status_id',
        foreignlanguage: 'foreign_language_id',
        vocationalcollege: 'vocational_college_id',
        vocationalmajor: 'vocational_major_id',
        candidateType: 'candidate_type_id',
        city: 'exam_center_city_id',
        major: 'exam_major_id',
        volunteercollege: 'volunteer_college_id',
        volunteermajor: 'volunteer_major_id'
    };

    const promises = [];

    Object.keys(mappingFields).forEach((field) => {
        const fieldId = mappingFields[field];
        const ids = this.getUniqueIds(fieldId);

        if (ids.length === 0) return;

        ids.forEach((id) => {
            if(field == "city"){
                const promise = http.get(`/${field}/info?id=${id}`).then((res) => {
                    if (res.statusCode === 200) {
                        const newName = res.data.cityName || '未知';
                        this.setData({
                            [`idToNameMappings.${field}.${id}`]: newName
                        });
                    } else {
                        console.error(`Error fetching ${field} info for id ${id}:`, res.data.message);
                    }
                }).catch((err) => {
                    console.error(`Error fetching ${field} info for id ${id}:`, err);
                });
                promises.push(promise);
            }
            else{
                const promise = http.get(`/${field}/info?id=${id}`).then((res) => {
                    if (res.statusCode === 200) {
                        const newName = res.data.data.name || '未知';
                        this.setData({
                            [`idToNameMappings.${field}.${id}`]: newName
                        });
                    } else {
                        console.error(`Error fetching ${field} info for id ${id}:`, res.data.message);
                    }
                }).catch((err) => {
                    console.error(`Error fetching ${field} info for id ${id}:`, err);
                });
    
                promises.push(promise);
            }
        });
    });

    // 等待所有请求完成后更新加载状态
    Promise.all(promises).then(() => {
        console.log('All mappings fetched successfully.');
        this.setData({ mappingsLoaded: true });
    }).catch((err) => {
        console.error('Error fetching all mappings:', err);
    });
},


getUniqueIds(fieldId) {
  const ids = new Set();
  const { baseCandidateInfo, baomingCandidateInfo, postCandidateInfo } = this.data;

  // 检查所有字段
  [baseCandidateInfo, baomingCandidateInfo, postCandidateInfo].forEach((info) => {
      if (info[fieldId]) {
          ids.add(info[fieldId]);
      }
  });

  return Array.from(ids);
},


  toggleSection(e) {
    const { section } = e.currentTarget.dataset;
    this.setData({
      [`expanded.${section}`]: !this.data.expanded[section]
    });
  },

  navigateToEdit(e) {
    const { section } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/edit-${section}/edit-${section}`
    });
  }
});
